import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fronter_service/api/cartApi.dart';
import 'package:flutter_fronter_service/api/goodsApi.dart';
import 'package:flutter_fronter_service/enum/BuyOrCart.dart';
import 'package:flutter_fronter_service/model/properties_entity.dart';
import 'package:flutter_fronter_service/widget/SkuShowModal.dart';
import 'package:get/get.dart';

import '../controller/userController.dart';
import '../model/goods_detail_entity.dart';
import '../model/sku_entity.dart';
import '../tools/commons.dart';
import '../widget/DottedDivider.dart';
import '../widget/PageViewSlid.dart';



class GoodsDetailPage extends StatefulWidget {
  const GoodsDetailPage({super.key});


  @override
  State<GoodsDetailPage> createState() => _GoodsDetailPageState();
}

class _GoodsDetailPageState extends State<GoodsDetailPage> {


  late RxList<SkuEntity> skuList = <SkuEntity>[].obs;
  late Rx<GoodsDetailEntity> goodsDetail = GoodsDetailEntity().obs;
  UserController userController = Get.find<UserController>();
  late SkuShowModal skuModal;

  Future<void> getGoodsList() async {
    //接收参数
    int id = await Get.arguments["id"];
    var res = await getGoodsDetailApi(id);

    //解析sku
    for(int i=0;i<res["data"]["skus"].length;i++){
      //规格列表
      late RxList<PropertiesEntity> itemSpecList = <PropertiesEntity>[].obs;
      //属性解析
      res["data"]["skus"][i]["itemSpec"].forEach((item)=>itemSpecList.add(PropertiesEntity.fromJson(item)));
      SkuEntity sku = SkuEntity.fromJson(res["data"]["skus"][i]);
      sku.itemSpec =  itemSpecList;
      skuList.add(sku);
    }

    //解析商品detail
    late RxList<PropertiesEntity> propList = <PropertiesEntity>[].obs;
    res["data"]["properties"].forEach((item)=>propList.add(PropertiesEntity.fromJson(item)));
    goodsDetail = GoodsDetailEntity.fromJson(res["data"]).obs;
    goodsDetail.value.skuList =  skuList;
    goodsDetail.value.propList = propList;

    setState(() {
      skuModal = SkuShowModal(skuList:skuList, goods_thumb: goodsDetail.value.picture, price: goodsDetail.value.price);
    });  // 重新build
  }

  List<Widget> generateDetail() {
    var tempList = goodsDetail.value.propList.map((prop) {
      return Column(
        children: [
          ListTile(
            leading: Text(
              prop.name,
              style: const TextStyle(color: Colors.black, fontWeight: FontWeight.w400, fontSize: 13),
            ),
            title: Text(
              prop.value,
              style: const TextStyle(color: Colors.black45, fontWeight: FontWeight.bold, fontSize: 12),
            ),
          ),
          DottedDivider(height: 1, color: Colors.grey,horizontalPadding: 10,),  // 使用虚线分隔线
        ],
      );
    }).toList();

    return tempList;
  }

  @override
  void initState() {
    super.initState();
    getGoodsList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品详情'),
      ),
      body:Obx(() => Stack(
        children: [
          ListView(
              children: [
                PageViewSlid(duration: 3000, imageList: goodsDetail.value.mainPictures,isUseIndexDots: false,height: 250,),
                Container(
                  padding: const EdgeInsets.only(left: 10,top: 5,bottom: 5),
                  width: double.infinity,
                  height: 50,
                  color: Colors.red,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("折后￥ ${goodsDetail.value.price.toString()}起",style: const TextStyle(color: Colors.white,fontSize: 15,fontWeight: FontWeight.bold),),
                      Text("全网热销9000+",style: const TextStyle(color: Colors.white,fontSize: 10),),
                    ],
                  ),
                ),
                ListTile(
                  title: Text(goodsDetail.value.name,style: const TextStyle(color: Colors.black,fontWeight: FontWeight.bold,fontSize: 15),),
                  subtitle: Text(goodsDetail.value.description,style: const TextStyle(color: Colors.black54,fontSize: 10)),
                ),
                Container(height: 10,color: Colors.black12,),
                Container(
                  padding: const EdgeInsets.only(left: 10),
                  color: Colors.white,
                  child: ListView(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    children:  [
                      const ListTile(
                        leading: Icon(Icons.details,size: 11,),
                        title: Text("详情",style: TextStyle(color: Colors.black45,fontWeight: FontWeight.bold,fontSize: 12),),
                        trailing: Icon(Icons.keyboard_arrow_right,size: 11,),
                      ),
                      ...generateDetail(),
                    ],
                  ),
                ),
                SizedBox(
                  child: Image.network("https://yanxuan-item.nosdn.127.net/a8d266886d31f6eb0d7333c815769305.jpg"),
                ),
                SizedBox(
                  child: Image.network(goodsDetail.value.descPictures),
                ),
                const SizedBox(
                  height: 55,
                ),
              ]
          ),
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            color: Colors.white,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                    alignment: Alignment.center,
                    child: const Column(
                      children: [
                        Icon(Icons.star_border),
                        Text(
                          "收藏",
                          style: TextStyle(fontSize: 10),
                        )
                      ],
                    )),
                Container(
                    alignment: Alignment.center,
                    child: const Column(
                      children: [
                        Icon(Icons.shopping_cart_outlined),
                        Text(
                          "购物车",
                          style: TextStyle(fontSize: 10),
                        )
                      ],
                    )),
                Container(
                    alignment: Alignment.center,
                    child: const Column(
                      children: [
                        Icon(Icons.headset_mic_outlined),
                        Text(
                          "客服",
                          style: TextStyle(fontSize: 10),
                        )
                      ],
                    )),
                userController.user.value.id>0?
                Container(
                  child: Row(
                    children: [ElevatedButton(
                      onPressed: () async {
                        var result = await skuModal.showSkuModal(context,BuyOrCart.Buy);
                        if(result!=null){

                          Get.toNamed("/confirmOrder",arguments: {"sku":[result]});
                        }else{
                          CommonUtils.showBotToast("请选择商品");
                        }
                      },
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                      child: const Text("立即购买",style: TextStyle(color: Colors.white),),
                    ),
                      ElevatedButton(
                        onPressed: () async {
                          var result = await skuModal.showSkuModal(context,BuyOrCart.Cart);
                          if(result!=null){
                            var res = await saveCartApi(result);
                            if(res["data"].runtimeType.toString()=="_Map<String, dynamic>"&&res["data"]["id"] >0){
                              CommonUtils.showBotToast("加入购物车成功");
                            }else{
                              CommonUtils.showBotToast("加入失败");
                            }
                          }
                        },
                        style: ElevatedButton.styleFrom(backgroundColor: Colors.orange),
                        child: const Text("加入购物车",style: TextStyle(color: Colors.white),),
                      ),],
                  )
                ):ElevatedButton(
                  onPressed: () async {
                    Get.toNamed("/login");
                  },
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                  child: const Text("登陆立即购买",style: TextStyle(color: Colors.white),),
                )
              ],
            ),
          ),
        )],
      ))
    );
  }
}
